package com.atstudying.mall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atstudying.common.constant.ProductConstant;
import com.atstudying.common.to.SkuHasStockVo;
import com.atstudying.common.to.SkuReductionTo;
import com.atstudying.common.to.SpuBoundTo;
import com.atstudying.common.to.es.SkuEsModel;
import com.atstudying.common.utils.PageUtils;
import com.atstudying.common.utils.Query;
import com.atstudying.common.utils.R;
import com.atstudying.mall.product.dao.SpuInfoDao;
import com.atstudying.mall.product.entity.*;
import com.atstudying.mall.product.feign.CouponSpuFeignService;
import com.atstudying.mall.product.feign.SearchFeignService;
import com.atstudying.mall.product.feign.WareFeignService;
import com.atstudying.mall.product.service.*;
import com.atstudying.mall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;
    @Autowired
    CouponSpuFeignService couponSpuFeignService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    AttrService attrService;
    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    SearchFeignService searchFeignService;
    @Autowired
    WareFeignService wareFeignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    //todo 高级部分完善

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo spuInfo) {

        //1：保存spu的基本信息SpuSaveVo（pms_spu_info）
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        BeanUtils.copyProperties(spuInfo,spuInfoEntity);
        this.saveBaseSpuInfo(spuInfoEntity);

        //1.1 保存它的描述decript（pms_spu_info_desc）
        List<String> decriptEntity = spuInfo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setDecript(String.join(",",decriptEntity));
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        //操作什么实体类就调用它对应的方法实现
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //1.2 保存它的图片集images（pms_spu_images）
        List<String> images = spuInfo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(),images);

        //1.3 保存spu的规格参数baseAttrs（pms_product_attr_value）
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map((item) -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setAttrId(item.getAttrId());
            //调用attrService里面的方法实时找到属性名
            AttrEntity byId = attrService.getById(item.getAttrId());
            productAttrValueEntity.setAttrName(byId.getAttrName());
            productAttrValueEntity.setAttrValue(item.getAttrValues());
            productAttrValueEntity.setQuickShow(item.getShowDesc());
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveBaseAttrs(collect);

        // 1.5 保存spu的积分信息bounds   mall-coupon-》sms_spu_bounds
        Bounds bounds = spuInfo.getBounds();
        //看数据可知，我们还要提交一个spu_id sms_spu_bounds封装成to提交
        SpuBoundTo spuBoundTo=new SpuBoundTo();
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        BeanUtils.copyProperties(bounds,spuBoundTo);
        R r= couponSpuFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode()!=0){

            log.error("远程保存spu积分信息失败");
        }

        //1.4 保存当前spu对应的所有sku信息skus  pms_sku_info
        // 1.4.1 sku的基本信息：（pms_sku_info）
        List<Skus> skus = spuInfo.getSkus();
        if (skus!=null && skus.size()>0){
            skus.forEach((item)->{
                String defaultImg="";
                for (Images images1:item.getImages()){
                    if (images1.getDefaultImg()==1){
                        defaultImg=images1.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
//                private String skuName;
//                private BigDecimal price;
//                private String skuTitle;
//                private String skuSubtitle;
                BeanUtils.copyProperties(item,skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoService.saveSkuInfo(skuInfoEntity);
                Long skuId = skuInfoEntity.getSkuId();

                // 1.4.2 sku的图片信息 images（pms_sku_images）
                List<SkuImagesEntity> skuImagesEntities = item.getImages().stream().map((image) -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setDefaultImg(image.getDefaultImg());
                    skuImagesEntity.setImgUrl(image.getImgUrl());
//                    skuImagesEntity.setImgSort(1);
                    return skuImagesEntity;
                }).filter((entities)->{
                    //返回true就是需要，返回false就是过滤掉
                    return !StringUtils.isEmpty(entities.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntities);

                // 1.4.3 sku的销售属性  attr （pms_sku_sale_attr_value）
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map((attrs) -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attrs, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                // 1.4.4 sku的优惠，满减等信息 mall-coupon-》sms_sku_ladder打折表，sms_sku_full_reduction满减表，sms_member_price会员价格
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount()>0 && skuReductionTo.getFullPrice().compareTo(new BigDecimal(0))==1){

                    R rs=couponSpuFeignService.saveSkuReduction(skuReductionTo);
                    if (rs.getCode()!=0){

                        log.error("远程保存spu积分信息失败");
                    }
                }
            });
        }




    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {

        this.baseMapper.insert(spuInfoEntity);
    }

    /**
     * spu检索
     * {
     page: 1,//当前页码
     limit: 10,//每页记录数
     sidx: 'id',//排序字段
     order: 'asc/desc',//排序方式
     key: '华为',//检索关键字
     catelogId: 6,//三级分类id
     brandId: 1,//品牌id
     status: 0,//商品状态
     }
     * @param params
     * @return
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){

            queryWrapper.and(w->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        //上面的 queryWrapper.and代表如下意思
        //status=1 and (id=1 or spu_name like xxx)
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);

        }


        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)){
            queryWrapper.eq("brand_id",brandId);

        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)){

           queryWrapper.eq("publish_status",status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),queryWrapper

        );

        return new PageUtils(page);
    }

    /**
     * 商品上架功能
     * @param spuId
     */
    @Override
    public void spuUp(Long spuId) {

//        List<SkuEsModel> uoProducts=new ArrayList<>();
        //1.组装需要的数据
//        SkuEsModel skuEsModel=new SkuEsModel();
        //1：查出当前spuid对应的所有sku信息，品牌名字
        List<SkuInfoEntity> skuInfoEntities= skuInfoService.getSkusBySpuId(spuId);

        List<Long> skuIdList = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        //todo 4：查询出当前sku的所有的可以被用来检索的规格属性（只要查一遍就可以了，放在stream外面来做
//            private List<Attrs> attrs;
//            @Data
//            public static class  Attrs{
//                private Long attrId;
//                private String attrName;
//                private StringBuilder attrValue;
////            }
//todo 4.1 检索出pms_product_attr_value中的AttrId的值通过spuId，然后在attrService中调用selectSearchAttrs过滤出search_type=0
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrlistforspu(spuId);
        log.error(String.valueOf(baseAttrs));
        List<Long> attrIds = baseAttrs.stream().map((attr) -> {

            return attr.getAttrId();
        }).collect(Collectors.toList());

        //todo 实现商品上架功能的时候，这里错误返回数据为0，导致es中保存不了，attrs的属性，以及下面的库存服务保存，理由是对应的xml文件写错了
        //从attrIds中过滤出我们想要的内容
        List<Long> searchAttrId = attrService.selectSearchAttrs(attrIds);

//        log.error(String.valueOf(searchAttrId));
        // todo 4.2 在baseAttrs中判断是否baseAttrs中的所有属性可以被上架，如果和searchAttrId相等就可以上架，并且保存在es中
        java.util.List<SkuEsModel.Attrs> attr=new ArrayList<>();
        HashSet<Long> idSet = new HashSet<>(searchAttrId);
//        log.error(String.valueOf(baseAttrs));

        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {

            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
//            log.error(String.valueOf(item));

            BeanUtils.copyProperties(item, attrs);
//            log.error(String.valueOf(attrs));

            return attrs;

        }).collect(Collectors.toList());

        log.error(String.valueOf(attrsList));
        //todo 1：发送远程调用，库存系统查询是否有库存 远程调用由于网络波动不稳定各种原因可呢会产生失败，下面就不会继续执行，我们可以设置成如果调用失败，继续往下走，默认有库存
        Map<Long, Boolean> stockMap=null;

        try {
            R r = wareFeignService.getSkusHasStock(skuIdList);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {

            };
            stockMap = r.getData("vos",typeReference).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        }catch (Exception e) {
            log.error("库存服务查询异常：原因{}", e);

        }


        //2：封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> collect = skuInfoEntities.stream().map((sku) -> {
            //1.组装需要的数据
            SkuEsModel skuEsModel = new SkuEsModel();
            //属性对拷
            BeanUtils.copyProperties(sku,skuEsModel);
            //SkuEsModel   SkuInfoEntity里面不一样的属性是：
            /**
             *     private BigDecimal skuPrice;
             private String skuImg;
             private Boolean hasStock;
             private Long hotScore;
             *   private String brandName;
             private String brandImg;
             private  String catalogName;
             private List<Attrs> attrs;
             @Data
             public static class  Attrs{
             private Long attrId;
             private String attrName;
             private StringBuilder attrValue;
             }
             */
//            private BigDecimal skuPrice;
//            private String skuImg;

            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());

//            private Boolean hasStock;
//            private Long hotScore;

            // todo 1：远程调用后设置库存信息
            if (finalStockMap ==null){
                skuEsModel.setHasStock(true);
            }else {
                skuEsModel.setHasStock(finalStockMap.get(sku.getSkuId()));

            }


            //todo 2：热度评分 0：应该是后台可控的复杂操作
            skuEsModel.setHotScore(0L);

            // todo 3：查询品牌和分类的名字信息
//            private String brandName;
//            private String brandImg;
            BrandEntity byId = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(byId.getName());
            skuEsModel.setBrandImg(byId.getLogo());
//            private  String catalogName;
            CategoryEntity byId1 = categoryService.getById(skuEsModel.getCatalogId());
            skuEsModel.setCatalogName(byId1.getName());
            //设置检索属性
            skuEsModel.setAttrs(attrsList);



            return skuEsModel;
        }).collect(Collectors.toList());

        // todo：5：将数据发送给es进行保存：mall-search

        R r = searchFeignService.productStatusUp(collect);
        if (r.getCode()==0){
            //远程调用成功
            // todo 6：修改当前spu状态
            baseMapper.updateStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());

        }else{
            //远程调用失败
            //todo 7：重复调用？接口幂等性，重新机制
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {

        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        SpuInfoEntity byId1 = getById(spuId);


        return byId1;
    }

}